// pages/temprature/temprature.js
Page({
  data: {
    text: '40℃'
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数

      // 添加网络连接
      var socketOpen = false
      // var socketMsgQueue = ['10001000'];

      // 定义发送的数据
      var buffer = new ArrayBuffer(8);
      var socketMsgQueue = new Uint32Array(buffer);
      socketMsgQueue[1] = 0x1;// vaule

      var socketMsg_u8 =  new Uint8Array(buffer); 
      socketMsg_u8[0] = 0x0; //保留位
      socketMsg_u8[1] = 0x0; //UI界面
      socketMsg_u8[2] = 0x0; //功能位
      socketMsg_u8[3] = 0x1; //发给谁

      wx.connectSocket({
        // 连接的网络域名
        url: 'wss://gec210.rfish.xyz:12345'
      })

      wx.onSocketOpen(function (res) {
        socketOpen = true
        // 发送数据
        sendSocketMessage(buffer);
        socketMsgQueue = []
      })

      function sendSocketMessage(msg) {
        if (socketOpen) {
          wx.sendSocketMessage({
            data: msg
          })

          wx.onSocketMessage(function (res) {
            // 检测接收数据的字节大小
            // var array_buff = new ArrayBuffer(64);

            // 读取ArrayBuffer数组   按照无符号整型读取   每一位代表一个字节
            var dataView_u8 = new Uint8Array(res.data);
            console.log(dataView_u8);

            var dv = new DataView(res.data);
            var v1 = dv.getUint8(0,false);
            var v2 = dv.getUint8(1,false);
            var v3 = dv.getUint8(2,false);
            var v4 = dv.getUint8(3,false);
            var v5 = dv.getUint8(4,false);
            var v6 = dv.getUint8(5,false);
            var v7 = dv.getUint8(6,false);
            var v8 = dv.getUint8(7,false);
            
            console.log(v1);
            console.log(v2);
            console.log(v3);
            console.log(v4);
            console.log(v5);
            console.log(v6);
            console.log(v7);
            console.log(v8);
            switch(v2){ 
              case 0:
                console.log('当前温度为'+v8);
              break;
                console.log('当前湿度为'+v8);
              case 1:
                console.log('当前光照为'+v8);                
              break;
              case 2:
                console.log('当MQ_2为' + v8);                                
              break;
              case 3:
                console.log('当前功能为' + v8);                                
              break;
            }
          })

        } else {
          socketMsgQueue.push(msg);
        }
      }

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})